/**
 * 招聘管理
 */
import React, { useEffect, Fragment, useState } from 'react';
import { connect } from 'umi';
import { history } from 'umi'
import { Form, Button, Table, Card, Input, Divider, Radio, message, Modal, Tooltip } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/pages/Setting/WebSite/RecruitManage/RecruitManage.less';
import LinkTo from '@/components/LinkTo';
import Pagination from '@/components/Pagination';
import AdvancedSearch from '@/components/AdvancedSearch';
import TableFilter from '@/components/TableFilter';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import { withRoutePage } from '@/utils/enhanceUtils';
// import routerReplace from '@/utils/routerReplace';
import { SearchInput } from '@/components/UserForm';
import { getPostType } from '@/services/setting/recruitManage';
// import SearchForm from './Components/SearchForm';

const { checkCode } = authHelper;

const ORDER_MAP = { ASC: 'ascend', DESC: 'descend' };

const RecruitList = ({ form, dispatch, loading, recruitManage, route, location }) => {
    const { getFieldDecorator } = form;
    const { query } = location;
    const { authCode } = new AuthCode(route.code);

    const { pagination, orderBy, recruitList } = recruitManage;
    const { workNature: initWorkNature } = query;
    const [workNature, setWorkNature] = useState(
        typeof initWorkNature === 'string' ? [initWorkNature] : initWorkNature
    );
    const [visible, setVisible] = useState(false);
    const [deleteVisible, setDeleteVisible] = useState(false);
    const [recordList, setRecordList] = useState(null);
    const [sortType, setSortType] = useState(true);
    const [editable, setEditable] = useState(false);
    const [sorterInfo, setSorterInfo] = useState();
    const [filtersInfo, setFiltersInfo] = useState();

    const getPayload = type => {
        const { postName, postType = [], workPlace = [] } = form.getFieldsValue();
        const finalPostType = typeof postType === 'string' ? postType.split(',') : postType;
        const finalWorkPlace = typeof workPlace === 'string' ? workPlace.split(',') : workPlace;
        const payload = {
            postName: postName || '',
            postType: finalPostType,
            workPlace: finalWorkPlace,
            sort: orderBy,
            workNature,
            pageNo: type ? 1 : pagination.current,
            pageSize: type ? 10 : pagination.pageSize
        };
        return payload;
    };

    const fetchRecruitList = type => {
        history.push({ query: getPayload(type) });
        dispatch({
            type: 'recruitManage/fetchRecruitList',
            payload: getPayload(type)
        });
    };

    // 设置职位是否隐藏
    const setPostType = record => {
        form.setFieldsValue({
            hidden: record.hidden.toString()
        });
        setRecordList(record);
        setVisible(true);
    };

    const handleDelPostType = record => () => {
        setRecordList(record);
        setDeleteVisible(true);
    };

    const [tableColumns, setTableColumns] = useState([]);

    const columns = [
        {
            title: '职位名称',
            dataIndex: 'postCnName',
            render: (text, record) => (
                <div style={{ width: 200, position: 'relative' }}>
                    <div
                        style={{
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            marginBottom: 0
                        }}
                    >
                        {checkCode(authCode('edit')) ? (
                            <LinkTo
                                className={styles.LinkTo}
                                title={record.postCnName}
                                to="/office/info/webSite/recruitList/recruitEdit"
                                query={{
                                    id: record.id,
                                    recruitmentCode: record.recruitmentCode,
                                    action: 'edit'
                                }}
                            >
                                {record.postCnName}
                            </LinkTo>
                        ) : (
                            record.postCnName
                        )}
                    </div>
                </div>
            )
        },
        ...tableColumns,
        {
            title: '职位类型',
            dataIndex: 'postCnType',
            width: '14%',
            className: styles.row
        },
        {
            title: '工作地点',
            dataIndex: 'workPlace',
            width: '8%',
            className: styles.workPlace,
            render: text => (text === 0 ? '厦门' : '新加坡')
        },
        {
            title: '工作性质',
            dataIndex: 'workNature',
            filters: [
                {
                    text: '全职',
                    value: '0'
                },
                {
                    text: '兼职',
                    value: '1'
                },
                {
                    text: '实习',
                    value: '2'
                }
            ],
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            width: 120,
            className: styles.workPlace,
            filteredValue: typeof workNature === 'string' ? [workNature] : workNature,
            render: text => {
                if (text === 0) {
                    return '全职';
                }
                if (text === 1) {
                    return '兼职';
                }
                return '实习';
            }
        },
        {
            title: '发布时间',
            dataIndex: 'releaseTime',
            width: '14%',
            className: styles.row,
            sortOrder: ORDER_MAP[orderBy] || false,
            sorter: () => {}
        },
        {
            title: '发布人',
            dataIndex: 'recriutReleaseUser',
            width: '15%',
            className: styles.row
        },
        {
            title: '隐藏职位',
            dataIndex: 'hidden',
            className: styles.workPlace,
            render: (text, record) => {
                if (record.hidden === 0) {
                    return (
                        <Tooltip placement="top" title="此职位为隐藏状态，不在官网职位列表显示">
                            是
                        </Tooltip>
                    );
                }
                if (record.hidden === 1) {
                    return '否';
                }
                return '';
            }
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            fixed: 'right',
            render: (text, record) => (
                <Fragment>
                    <a
                        onClick={() => {
                            history.push({
                                pathname: '/office/info/webSite/recruitList/recruitEdit',
                                query: {
                                    id: record.id,
                                    recruitmentCode: record.recruitmentCode,
                                    action: 'edit'
                                }
                            });
                        }}
                        disabled={!checkCode(authCode('edit'))}
                    >
                        编辑
                    </a>
                    <Divider type="vertical" />
                    <a
                        disabled={!checkCode(authCode('set'))}
                        onClick={() => {
                            setPostType(record);
                        }}
                    >
                        设置
                    </a>
                    <Divider type="vertical" />
                    <a onClick={handleDelPostType(record)} disabled={!checkCode(authCode('delete'))}>
                        删除
                    </a>
                </Fragment>
            ),
            width: 160
        }
    ];

    // 表格表头点击切换排序
    const changeTable = async (paginations, filters, sorter) => {
        const extra = {};
        if (filtersInfo !== filters) {
            extra.current = 1;
            setFiltersInfo(filters);
        }
        if (sorterInfo !== sorter) {
            extra.current = 1;
            setSorterInfo(sorter);
        }
        let orderBys;
        if (sorter && sorter.field && sorter.order) {
            const order =
                sorter.order &&
                sorter.order
                    .trim()
                    .split('end')[0]
                    .toUpperCase();

            orderBys = order;
        }
        if (filters && filters.workNature) {
            console.log(filters.workNature, 'filters.workNature');
            if (filters.workNature[0] === 'all') {
                setWorkNature(['0', '1', '2']);
            } else if (filters.workNature.length === 0) {
                setWorkNature([]); // 修复无法置空的问题，因为空数组会被routerReplace忽略掉
            } else {
                setWorkNature(filters.workNature);
            }
        }
        // fetchRecruitList(true);
        await dispatch({
            type: 'recruitManage/save',
            payload: {
                orderBy: orderBys || '',
                pagination: {
                    ...recruitManage.pagination,
                    ...paginations,
                    ...extra
                }
            }
        });
    };

    const extra = (
        <Fragment>
            <AuthComponent code={authCode('add')}>
                <Button
                    type="primary"
                    onClick={() => {
                        history.push({
                            pathname: '/office/info/webSite/recruitList/recruitEdit'
                        });
                    }}
                >
                    发布职位
                </Button>
            </AuthComponent>
        </Fragment>
    );

    const sortInputCheck = (rule, value, callback) => {
        if (!value) {
            message.error('请输入排序');
            callback(false);
        }
        if (!/^[^-0][0-9]{0,2}$/.test(value)) {
            message.error('请输入四位数以内的整数');
            callback(false);
        }
        callback();
    };

    const renderItem = record => (
        <Form.Item style={{ marginBottom: 0 }} className={styles.sortForm}>
            {getFieldDecorator(`sort-${record.id}`, {
                initialValue: record.reSort,
                rules: [
                    {
                        validator: sortInputCheck
                    }
                ]
            })(<Input style={{ width: '100%' }} size="small" maxLength={3} />)}
        </Form.Item>
    );

    // 保存排序的值
    const saveSort = () => {
        const values = form.getFieldsValue();
        const { hidden, postName, postType, workPlace, ...otherData } = values;
        let sortIds = [];
        let isCheck = true; // 设立中间变量 如何通过了可以发起请求，不通过，提示错误，并且清空数组字段
        Object.keys(otherData).forEach(prop => {
            sortIds.push(`${prop.split('-')[1]}@${otherData[prop]}`);
            if (otherData[prop] === '' || !/^[^-0][0-9]{0,2}$/.test(otherData[prop])) {
                isCheck = false;
                sortIds = [];
            }
        });
        if (isCheck) {
            dispatch({
                type: 'recruitManage/fetchSort',
                payload: {
                    sortIds: sortIds.join()
                },
                callback: res => {
                    if (res.code === 10000) {
                        message.success(res.msg);
                        setTableColumns([]);
                        fetchRecruitList();
                        setSortType(!sortType);
                        setEditable(false);
                    } else {
                        message.error(res.msg);
                    }
                }
            });
        } else {
            message.error('请输入四位数以内的整数');
        }
    };

    // 设置排序
    const setSort = () => {
        const addColumns = {
            title: '排序',
            dataIndex: 'reSort',
            editable: true,
            width: 80,
            render: (text, record, index) => <div style={{ width: 80 }}>{renderItem(record, index)}</div>
        };
        setTableColumns([addColumns]);
        setEditable(true);
    };

    // 对话窗确认
    const handleOk = () => {
        form.validateFields(['hidden'], (err, values) => {
            if (!err) {
                dispatch({
                    type: 'recruitManage/fetchHide',
                    payload: {
                        hidden: values.hidden,
                        id: recordList.id
                    },
                    callback: res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            fetchRecruitList();
                            setVisible(false);
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            }
        });
    };

    // 取消
    const handleCancel = () => {
        form.resetFields(['hidden']);
        setVisible(false);
    };

    const handleDeleteOk = () => {
        dispatch({
            type: 'recruitManage/fetchDelect',
            payload: {
                id: recordList.id,
                code: recordList.recruitmentCode
            },
            callback: res => {
                if (res.code === 10000) {
                    message.success(res.msg);
                    fetchRecruitList();
                    setDeleteVisible(false);
                } else {
                    message.error(res.msg);
                }
            }
        });
    };

    const handleDeleteCancel = () => {
        setDeleteVisible(false);
    };

    const onSearch = type => () => {
        fetchRecruitList(type);
    };

    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'recruitManage/save',
                payload: {
                    orderBy: '',
                    pagination: {
                        pageSize: 10,
                        current: 1,
                        total: 0
                    }
                }
            });
        },
        []
    );

    useEffect(() => {
        form.setFieldsValue(query);
        fetchRecruitList();
    }, [pagination.pageSize, pagination.current, orderBy, workNature]);

    const extraBtn = (
        <AuthComponent code={authCode('sort')}>
            {editable ? <Button onClick={saveSort}>保存排序</Button> : <Button onClick={setSort}>设置排序</Button>}
        </AuthComponent>
    );

    return (
        <PageHeaderWrapper>
            <Card bordered={false} title="招聘需求" extra={extra}>
                {/* <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        marginBottom: 15
                    }}
                >
                    <SearchForm form={form} onSearch={onSearch(true)} />
                    <AuthComponent code={authCode('sort')}>
                        {editable ? (
                            <Button onClick={saveSort}>保存排序</Button>
                        ) : (
                            <Button onClick={setSort}>设置排序</Button>
                        )}
                    </AuthComponent>
                </div> */}
                <AdvancedSearch form={form} onSubmit={onSearch(true)} onReset={onSearch(true)} extraButtons={extraBtn}>
                    <Form.Item label="职位">
                        {getFieldDecorator('postName', {})(<Input placeholder="输入关键词搜索更多职位" allowClear />)}
                    </Form.Item>
                    <Form.Item label="职位类型">
                        {getFieldDecorator(
                            'postType',
                            {}
                        )(
                            <SearchInput
                                getData={params =>
                                    getPostType(params).then(res => {
                                        if (res && res.code === 10000 && res.data) {
                                            return res.data || [];
                                        }
                                        return [];
                                    })
                                }
                                fieldsName={{
                                    value: 'value',
                                    title: 'name'
                                }}
                                selectProps={{
                                    placeholder: '请选择职位类型',
                                    // style: { width: 200 },
                                    mode: 'multiple',
                                    maxTagCount: 3
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="工作地点">
                        {getFieldDecorator(
                            'workPlace',
                            {}
                        )(
                            <SearchInput
                                getData={() => {
                                    const arr = [
                                        {
                                            title: '厦门',
                                            value: '0'
                                        },
                                        {
                                            title: '新加坡',
                                            value: '1'
                                        }
                                    ];
                                    return arr;
                                }}
                                fieldsName={{
                                    value: 'value',
                                    title: 'title'
                                }}
                                selectProps={{
                                    placeholder: '请选择工作地点',
                                    // style: { width: 200 },
                                    mode: 'multiple',
                                    maxTagCount: 3
                                }}
                            />
                        )}
                    </Form.Item>
                </AdvancedSearch>
                <Table
                    loading={loading}
                    dataSource={recruitList}
                    columns={columns}
                    scroll={{ x: 'max-content' }}
                    onChange={changeTable}
                    rowKey="id"
                    pagination={false}
                />
                <Pagination
                    {...pagination}
                    onChange={changeTable}
                    filters={filtersInfo}
                    sorter={sorterInfo}
                    loading={loading}
                />
                <Modal title="职位设置" visible={visible} onOk={handleOk} onCancel={handleCancel}>
                    <Form layout="inline">
                        <Form.Item label="是否隐藏职位">
                            {getFieldDecorator('hidden', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择是否隐藏职位'
                                    }
                                ]
                            })(
                                <Radio.Group>
                                    <Radio value="0">是</Radio>
                                    <Radio value="1">否</Radio>
                                </Radio.Group>
                            )}
                            <div
                                style={{
                                    color: 'rgba(0, 0, 0, 0.45)',
                                    marginTop: '-10px'
                                }}
                            >
                                隐藏的职位不再官网职位列表中显示
                            </div>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title="删除职位" visible={deleteVisible} onOk={handleDeleteOk} onCancel={handleDeleteCancel}>
                    确定要删除这项职位？删除后此职位信息消失，不可恢复！
                </Modal>
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ loading, recruitManage }) => ({ recruitManage, loading: loading.models.recruitManage }))(
        Form.create()(RecruitList)
    )
);
